package com.fsd.admin.listener.activiti;

import com.fsd.core.util.DateTimeUtil;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.el.FixedValue;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * ================================
 * @Description: 时间检查任务监听
 * @Author: lumingbao
 * @Date 2019-01-02 15:11
 * ================================
 */
public class TimeCheckTaskListener implements TaskListener {

    /**
     * 最小时间限制
     */
    public FixedValue minitime;

    @Override
    public void notify(DelegateTask delegateTask) {
        String minitimeStr = minitime.getExpressionText();

        int day = DateTimeUtil.differentDays(new Date(), delegateTask.getCreateTime());

        System.out.println("执行时长：" + day);

        String miniDay = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(delegateTask.getCreateTime());
        if(minitimeStr.indexOf(">=") != -1){
            miniDay = minitimeStr.substring(2, minitimeStr.length());
            System.out.println("最小时间限制为：" + miniDay);
            calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(miniDay));
            if(day < Integer.valueOf(miniDay)){
                throw new ActivitiException("该节点最短时间要求为：" + miniDay + "天，具体时间节点为：" + formatter.format(calendar.getTime()) + "，在此时间节点前无法提交该任务！");
            }
        }else{
            miniDay = minitimeStr.substring(1, minitimeStr.length());
            System.out.println("最小时间限制为：" + miniDay);
            calendar.add(Calendar.DAY_OF_MONTH, Integer.valueOf(miniDay));
            if(day <= Integer.valueOf(miniDay)){
                throw new ActivitiException("该节点最短时间要求为：" + miniDay + "天，具体时间节点为：" + formatter.format(calendar.getTime()) + "，在此时间节点前无法提交该任务！");
            }
        }
    }

    public FixedValue getMinitime() {
        return minitime;
    }
    public void setMinitime(FixedValue minitime) {
        this.minitime = minitime;
    }
}
